package Commands;

import domain.Subject;

import domain.Controller;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CmdGetValgfagsPuljer extends Command
{
  Controller controller;
  String nextJspUrl = 
    "userStory4.jsp"; 

  public void init(CommandFactory comFac, Controller c)
    throws ServletException 
  {
    this.controller = c;
  }

  public void execute(HttpServletRequest request, HttpServletResponse resp)
    throws ServletException 
  {    
    HttpSession session = request.getSession(true);  
    controller.clearPuljer();
    if(request.getParameter("subject")==null&&request.getParameter("subject2")==null)
    {
      controller.getPuljer();
      session.setAttribute("pulje1",controller.getPulje1());
      session.setAttribute("pulje2",controller.getPulje2()); 
    }
      //String init = (String)session.getAttribute("init");
      //if(!init.equals("first")) 
    nextJspUrl = request.getParameter("ref") + ".jsp";
    if(request.getParameter("subject")!=null)
    {
      String[] subs = request.getParameterValues("subject");
      List<Subject> subsList = new ArrayList<Subject>();
      for(int i = 0; i < subs.length; i++)
      {
        Subject su = controller.getSubject(Integer.parseInt(subs[i]));
        controller.addPulje1(su);
        if(!subsList.contains(su))
          subsList.add(su);
        System.out.println("Checking1" + su.getId());
      }      
      session.setAttribute("pulje1",subsList);
    }
    if(request.getParameter("subject2")!=null)
    {
      String[] subs2 = request.getParameterValues("subject2");
      List<Subject> subs2List = new ArrayList<Subject>();
      for(int i = 0; i < subs2.length; i++)
      {
        Subject su = controller.getSubject(Integer.parseInt(subs2[i]));
        controller.addPulje2(su);
        if(!subs2List.contains(su))
          subs2List.add(su);
        System.out.println("Checking2" + su.getId());
      }      
      session.setAttribute("pulje2",subs2List);
    }
    session.setAttribute("subjects",controller.getAllSubjects());
    if(request.getParameter("ref").equals("userStory4"))
      controller.checkPuljer();
    else
      controller.checkPuljer2();
    session.setAttribute("students",controller.getStudents());
  }
  
  public String getNextJspUrl()
  {
    return nextJspUrl;
  }
}
